#!/usr/bin/perl -w

#=======================================================================
# create_imgindex
# File ID: e315d656-1cb0-11de-a0da-000475e441b9
# Create HTML page with collection of images
#
# Character set: UTF-8
# ©opyleft 2004– Øyvind A. Holm <sunny@sunbase.org>
# License: GNU General Public License version 2 or later, see end of 
# file for legal stuff.
#=======================================================================

use strict;
use Getopt::Long;

$| = 1;

our $Debug = 0;

our %Opt = (

    'debug' => 0,
    'generate' => 0,
    'help' => 0,
    'language' => "en",
    'output-file' => "",
    'title' => "",
    'verbose' => 0,
    'version' => 0,

);

our $progname = $0;
$progname =~ s/^.*\/(.*?)$/$1/;
our $VERSION = "0.00";

my $Author = txt_to_xml('Øyvind A. Holm <sunny@sunbase.org>'); # FIXME: Hardcoding
my $cmdline_str = txt_to_xml(join(" ", @ARGV));

Getopt::Long::Configure("bundling");
GetOptions(

    "debug" => \$Opt{'debug'},
    "generate|g" => \$Opt{'generate'},
    "help|h" => \$Opt{'help'},
    "language|l=s" => \$Opt{'language'},
    "output-file|o=s" => \$Opt{'output-file'},
    "title|t=s" => \$Opt{'title'},
    "verbose|v+" => \$Opt{'verbose'},
    "version" => \$Opt{'version'},

) || die("$progname: Option error. Use -h for help.\n");

$Opt{'debug'} && ($Debug = 1);
$Opt{'help'} && usage(0);
if ($Opt{'version'}) {
    print_version();
    exit(0);
}

my $Title = txt_to_xml($Opt{'title'}) || die("$progname: -t/--title not specified\n");;
my $Outfile = txt_to_xml($Opt{'output-file'}) || die("$progname: -o/--output-file not specified\n");;
scalar(@ARGV) || die("$progname: No filenames specified\n");

my $is_svn_wc = -d ".svn/." ? 1 : 0;

for my $Dir (qw{4288x2848 2144x1424 1072x712 536x356 thumbs}) {
    if (!-d "$Dir/.") {
        mkdir($Dir) || die("$progname: $Dir: mkdir() error: $!\n");
        $is_svn_wc && mysyst("svn", "add", $Dir);
    }
    if (!-e "$Dir/.htaccess") {
        open(OutFP, ">$Dir/.htaccess") || die("$progname: $Dir/.htaccess: Cannot create file: $!\n");
        chomp(my $file_id = `fileid -t htaccess $Dir/.htaccess`);
        print(OutFP <<END);
$file_id

DirectoryIndex SpesialIndex.html
Options Indexes
IndexOptions FancyIndexing NameWidth=* DescriptionWidth=*
AddType text/plain;charset=UTF-8 txt
AddType text/html;charset=UTF-8 html
AddDefaultCharset UTF-8
END
        close(OutFP);
        if ($is_svn_wc) {
            mysyst("svn", "add", "$Dir/.htaccess");
            mysyst("keyw", "$Dir/.htaccess");
        }
    }
}

my @time_array = localtime(time);
my $Year = $time_array[5] + 1900;

my $files_str = "";
my %smsum = ();
my @files_found = ();

open(OutFP, ">", $Outfile) || die("$progname: $Outfile: Cannot create file: $!\n");

for my $t (@ARGV) {
    if (-r $t) {
        msg(0, "$t");
        chomp($smsum{$t} = `smsum <$t`);
        $files_str .= sprintf("<file> <name>%s</name> <smsum>%s</smsum> </file> ", txt_to_xml($t), $smsum{$t});
        if ($Opt{'generate'}) {
            mysyst("cp -Lp $t 4288x2848/$t");
            mysyst("convert -resize 2144 4288x2848/$t 2144x1424/$t");
            mysyst("convert -resize 1072 2144x1424/$t 1072x712/$t");
            mysyst("convert -resize 536 1072x712/$t 536x356/$t");
            mysyst("convert -resize 160 536x356/$t thumbs/$t");
        }
        push(@files_found, $t);
    } else {
        warn("$progname: $t: Cannot open file for read: $!\n");
    }
}

chomp(my $uuid = `suuid -t create_imgindex --raw -c "<c_create_imgindex> <cmdline>$cmdline_str</cmdline> <filename>$Outfile</filename> $files_str</c_create_imgindex>"`)
    || die("$progname: suuid error");

my $ignorefile = ".$uuid.ignore.tmp";
if ($is_svn_wc) {
    if (open(TmpFP, ">", $ignorefile)) {
        printf(TmpFP "%s\n", join("\n", @files_found));
        close(TmpFP);
    }
}
if ($Opt{'generate'}) {
    for my $dir (qw{4288x2848 2144x1424 1072x712 536x356 thumbs}) {
        if (chdir($dir)) {
            mysyst("mkFiles");
            if ($is_svn_wc) {
                mysyst("svn add Files.smsum");
            }
            chdir("..");
        } else {
            warn("$progname: $dir: Cannot chdir(), mkFiles not executed: $!\n");
        }
        $is_svn_wc && mysyst("svn -F $ignorefile ps svn:ignore $dir");
    }
}
$is_svn_wc && unlink($ignorefile);

print(OutFP <<END);
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="$Opt{'language'}" lang="$Opt{'language'}">
  <!-- File ID: $uuid -->
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>$Title</title>
    <style type="text/css">
      <!--
      body { background-color: white; color: black; font-family: sans-serif; }
      a:link { color: blue; background-color: white; }
      a:visited { color: maroon; background-color: white; }
      a:active { color: fuchsia; background-color: white; }
      h1 { text-align: center; font-size: 200%; font-weight: bold; }
      h2 { text-align: center; font-size: 120%; font-weight: bold; }
      table.main { margin: 0 auto; }
      td.head { text-align: center; vertical-align: middle; }
      td.dirtxt { text-align: left; vertical-align: middle; }
      td.dirs { text-align: center; vertical-align: middle; width: 25%; }
      td.image { text-align: center; vertical-align: middle; }
      td.text { text-align: center; vertical-align: top; font-size: 80%; }
      td.lefticon { text-align: center; vertical-align: middle; font-size: 80%; }
      td.righticon { text-align: center; vertical-align: middle; font-size: 80%; }
      td.footer { text-align: center; vertical-align: top; width: 100%; font-size: 100%; }
      -->
    </style>
    <meta name="author" content="Øyvind A. Holm — sunny\@sunbase.org" />
    <meta name="copyright" content="©$Year- Øyvind A. Holm" />
    <link rev="made" href="mailto:sunny\@sunbase.org" />
  </head>
  <body>
    <table class="main" cellpadding="10" cellspacing="0" border="1">
      <tr>
        <td class="head" colspan="4">
          <h1>$Title</h1>
          <table width="100%">
            <tr>
              <td colspan="4" class="dirtxt">
                <h2>Directories:</h2>
              </td>
            </tr>
            <tr>
              <td class="dirs">
                <a href="4288x2848/">4288x2848/</a>
              </td>
              <td class="dirs">
                <a href="2144x1424/">2144x1424/</a>
              </td>
              <td class="dirs">
                <a href="1072x712/">1072x712/</a>
              </td>
              <td class="dirs">
                <a href="536x356/">536x356/</a>
              </td>
            </tr>
          </table>
        </td>
      </tr>
END

my ($Count, $create_td) = (0, 0);

for my $Curr (@ARGV) {
    if (!$Count) {
      print(OutFP "      <tr>\n");
    }
    print(OutFP <<END);
        <td>
          <!-- $smsum{$Curr} -->
          <table width="100%" cellpadding="2" cellspacing="0" border="0">
            <tr>
              <td class="image" colspan="2">
                <img src="thumbs/$Curr" width="160" alt="$Curr" />
              </td>
            </tr>
            <tr>
              <td class="text">
                [<a href="4288x2848/$Curr">4288x2848</a>]<br />
                [<a href="1072x712/$Curr">1072x712</a>]
              </td>
              <td class="text">
                [<a href="2144x1424/$Curr">2144x1424</a>]<br />
                [<a href="536x356/$Curr">536x356</a>]
              </td>
            </tr>
            <tr>
              <td class="text" colspan="2">
                <b>$Curr</b>
              </td>
            </tr>
          </table>
        </td>
END
    $Count++;
    if ($Count > 3) {
        print(OutFP "      </tr>\n");
        $Count = 0;
        $create_td = 1;
    }
}

if ($Count) {
    $create_td && printf(OutFP "        <td colspan=\"%u\">\n        </td>\n", 4-$Count);
    print(OutFP "      </tr>\n");
}

print(OutFP <<END);
      <tr>
        <td colspan="4">
          <table cellpadding="5" cellspacing="0" border="0">
            <tr>
              <td class="lefticon">
                <a href="http://validator.w3.org/check?uri=referer"><img src="http://www.w3.org/Icons/valid-xhtml10.png" alt="Valid XHTML 1.0" width="88" height="31" style="border: 0;" /></a>
              </td>
              <td class="footer" colspan="2">
                ©opyleft $Year- Øyvind A. Holm &lt;sunny\@sunbase.org&gt;<br />
                License:
                <a rel="license" href="http://creativecommons.org/licenses/by-sa/3.0/">Creative Commons Attribution-Share Alike 3.0 Unported</a>
              </td>
              <td class="righticon">
                <a href="http://jigsaw.w3.org/css-validator/check/referer"><img src="http://www.w3.org/Icons/valid-css.png" alt="Valid CSS" width="88" height="31" style="border: 0;" /></a>
              </td>
            </tr>
          </table>
        </td>
      </tr>
    </table>
  </body>
</html>
END

close(OutFP);

sub mysyst {
    # {{{
    my @Args = @_;
    my $system_txt = sprintf("system(\"%s\");", join("\", \"", @Args));
    msg(1, "Executing '$system_txt'...");
    system(@_);
    # }}}
} # mysyst()

sub txt_to_xml {
    # {{{
    my $Txt = shift;
    $Txt =~ s/&/&amp;/gs;
    $Txt =~ s/</&lt;/gs;
    $Txt =~ s/>/&gt;/gs;
    return($Txt);
    # }}}
} # txt_to_xml()

sub print_version {
    # Print program version {{{
    print("$progname v$VERSION\n");
    # }}}
} # print_version()

sub usage {
    # Send the help message to stdout {{{
    my $Retval = shift;

    if ($Opt{'verbose'}) {
        print("\n");
        print_version();
    }
    print(<<END);

Usage: $progname [options] -o OUTFILE -t TITLE [images ...]

Options:

  -g, --generate
    Generate resized images in subdirectory tree. Needs convert(1) from 
    the ImageMagick package.
  -h, --help
    Show this help.
  -l X, --language X
    Use language code X. Default: "en".
  -o X, --output-file X
    Store output in file X.
  -t X, --title X
    Use title and header X.
  -v, --verbose
    Increase level of verbosity. Can be repeated.
  --version
    Print version information.
  --debug
    Print debugging messages.

END
    exit($Retval);
    # }}}
} # usage()

sub msg {
    # Print a status message to stderr based on verbosity level {{{
    my ($verbose_level, $Txt) = @_;

    if ($Opt{'verbose'} >= $verbose_level) {
        print(STDERR "$progname: $Txt\n");
    }
    # }}}
} # msg()

sub D {
    # Print a debugging message {{{
    $Debug || return;
    my @call_info = caller;
    chomp(my $Txt = shift);
    my $File = $call_info[1];
    $File =~ s#\\#/#g;
    $File =~ s#^.*/(.*?)$#$1#;
    print(STDERR "$File:$call_info[2] $$ $Txt\n");
    return("");
    # }}}
} # D()

__END__

# Plain Old Documentation (POD) {{{

=pod

=head1 NAME



=head1 SYNOPSIS

 [options] [file [files [...]]]

=head1 DESCRIPTION



=head1 OPTIONS

=over 4

=item B<-h>, B<--help>

Print a brief help summary.

=item B<-v>, B<--verbose>

Increase level of verbosity. Can be repeated.

=item B<--version>

Print version information.

=item B<--debug>

Print debugging messages.

=back

=head1 BUGS



=head1 AUTHOR

Made by Øyvind A. Holm S<E<lt>sunny@sunbase.orgE<gt>>.

=head1 COPYRIGHT

Copyleft © Øyvind A. Holm E<lt>sunny@sunbase.orgE<gt>
This is free software; see the file F<COPYING> for legalese stuff.

=head1 LICENCE

This program is free software: you can redistribute it and/or modify it 
under the terms of the GNU General Public License as published by the 
Free Software Foundation, either version 2 of the License, or (at your 
option) any later version.

This program is distributed in the hope that it will be useful, but 
WITHOUT ANY WARRANTY; without even the implied warranty of 
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along 
with this program.
If not, see L<http://www.gnu.org/licenses/>.

=head1 SEE ALSO

=cut

# }}}

# vim: set fenc=UTF-8 ft=perl fdm=marker ts=4 sw=4 sts=4 et fo+=w :
